//
//  TouchLockViewController.m
//  HuaRun2
//
//  Created by admin on 2017/11/9.
//  Copyright © 2017年 Sunny. All rights reserved.
//

#import "TouchLockViewController.h"
#import "UIButton+ImageTitleSpacing.h"
#import "LoginViewController.h"
#import "ZLGestureLockViewController.h"
#import <LocalAuthentication/LocalAuthentication.h>

@interface TouchLockViewController ()

//标题label
@property (nonatomic, strong) UILabel * titleLabel;
@property (nonatomic, strong) UILabel * statusLabel;

//账号登陆
@property (nonatomic, strong) UIButton * accountBtn;
//指纹登陆
@property (nonatomic, strong) UIButton * touchBtn;

@property (nonatomic, strong) UIImageView * iconView;


@end

@implementation TouchLockViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewInit {
  
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.titleLabel];
    [self.view addSubview:self.statusLabel];
    
    [self.view addSubview:self.accountBtn];
    [self.view addSubview:self.touchBtn];
    
    [self.view addSubview:self.iconView];
    
    
}

- (void)layoutInit {
    weakself(ws);
    
    CGFloat top = (self.view.frame.size.height - self.view.frame.size.width - 60)/2;
    [self.statusLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(ws.view);
        make.top.mas_equalTo(ws.view).offset(top + kMargin10);
        make.size.mas_equalTo(CGSizeMake(kMainScreenWidth, 20));
    }];
    
    [self.iconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(ws.view);
        make.size.mas_equalTo(CGSizeMake(87, 85));
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(ws.view);
        make.bottom.mas_equalTo(ws.statusLabel.mas_top).offset(-kMargin10);
        make.size.mas_equalTo(CGSizeMake(kMainScreenWidth, 20));
    }];
    
    [self.accountBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(ws.view);
        make.top.mas_equalTo(ws.view.mas_top).offset(kMainScreenWidth + top + kMargin10);
        make.size.mas_equalTo(CGSizeMake(kMainScreenWidth / 2, 60));
    }];
    
    [self.touchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(ws.view);
        make.size.top.mas_equalTo(ws.accountBtn);
    }];
    
}

- (void)dataInit {
    [_accountBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleTop     imageTitleSpace:kMargin10];
    [_touchBtn layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleTop     imageTitleSpace:kMargin10];
    [self authenticateUser];
}

#pragma mark - 按钮点击事件 Anction

// 点击账号登陆按钮
- (void)accountLoginMethod {
    LoginViewController *loginVC = [LoginViewController new];
    weakself(ws);
    loginVC.clickBlock = ^(id result) {
        [ws.navigationController dismissViewControllerAnimated:YES
                                                    completion:^{
                                                        
                                                    }];
    };
    [self.navigationController pushViewController:loginVC animated:YES];
}

// 点击忘记手势密码按钮
- (void)touchLoginMethod {
    ZLGestureLockViewController *loginVC =  [[ZLGestureLockViewController alloc] initWithUnlockType:ZLUnlockTypeValidatePsw];

    weakself(ws);
    loginVC.clickBlock = ^(id result) {
        [ws.navigationController dismissViewControllerAnimated:YES
                                                    completion:^{
                                                        
                                                    }];
    };
    [self.navigationController pushViewController:loginVC animated:YES];
}

- (void)backMethod {
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}

// 验证指纹
- (void)authenticateUser {
    //创建LAContext
    LAContext *context = [[LAContext alloc] init];
    // 这个属性是设置指纹输入失败之后的弹出框的选项
    context.localizedFallbackTitle = @"请输入密码";
    
    NSError *error = nil;
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
        NSLog(@"支持指纹识别");
        // localizedReason: 用于设置提示语，表示为什么要使用Touch ID
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:@"请按home键指纹解锁" reply:^(BOOL success, NSError * _Nullable error) {
            if (success) {
                dispatch_sync(dispatch_get_main_queue(), ^{
                    // Update UI in UI thread here
                    NSLog(@"验证成功 刷新主界面");
                    [self dismissViewControllerAnimated:YES completion:^{
                    
                    }];
                });
            }else{
                NSLog(@"%@",error.localizedDescription);
                switch (error.code) {
                    case LAErrorSystemCancel:
                    {
                        NSLog(@"系统取消授权，如其他APP切入");
                        break;
                    }
                    case LAErrorUserCancel:
                    {
                        NSLog(@"用户取消验证Touch ID");
                        break;
                    }
                    case LAErrorAuthenticationFailed:
                    {
                        NSLog(@"授权失败");
                        break;
                    }
                    case LAErrorPasscodeNotSet:
                    {
                        NSLog(@"系统未设置密码");
                        break;
                    }
                    case LAErrorTouchIDNotAvailable:
                    {
                        NSLog(@"设备Touch ID不可用，例如未打开");
                        break;
                    }
                    case LAErrorTouchIDNotEnrolled:
                    {
                        NSLog(@"设备Touch ID不可用，用户未录入");
                        break;
                    }
                    case LAErrorUserFallback: // 用于设置左边的按钮的名称，默认是Enter Password
                    {
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            NSLog(@"用户选择输入密码，切换主线程处理");
                        }];
                        break;
                    }
                    default:
                    {
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            NSLog(@"其他情况，切换主线程处理");
                        }];
                        break;
                    }
                }
            }
        }];
    }else{
        
        NSLog(@"不支持指纹识别");
        switch (error.code) {
            case LAErrorTouchIDNotEnrolled:
            {
                NSLog(@"TouchID is not enrolled");
                break;
            }
            case LAErrorPasscodeNotSet:
            {
                NSLog(@"A passcode has not been set");
                break;
            }
            default:
            {
                NSLog(@"TouchID not available");
                break;
            }
        }
        
        NSLog(@"%@",error.localizedDescription);
    }
}
#pragma mark getter setter
//        "setPhotoPsd" = "请设置图案密码";
//_statusLabel.text = NSLocalizedString(@"inputPhotoPsd", nil);
//touchLogin 指纹登录-指紋登錄-TouchID
- (UILabel *)statusLabel {
    if (!_statusLabel) {
        self.statusLabel = [UILabel new];
        _statusLabel.textAlignment = NSTextAlignmentCenter;
        _statusLabel.font = kFontSize15;
        _statusLabel.textColor = [UIColor grayColor];
        _statusLabel.text = NSLocalizedString(@"touchLogin", nil);
    }
    return _statusLabel;
}

//        "huanYingUse" = "欢迎使用CM系统";
//_titleLabel.text = NSLocalizedString(@"huanYingBack", nil);

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        self.titleLabel = [UILabel new];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.font = [UIFont boldSystemFontOfSize:20];
        _titleLabel.textColor = [UIColor orangeColor];
        _titleLabel.text = NSLocalizedString(@"huanYingBack", nil);
    }
    return _titleLabel;
}

//"useAccount" = "使用账号密码登陆";
- (UIButton *)accountBtn {
    if (!_accountBtn) {
        UIButton * btn = [UIButton new];
        [btn setImage:[UIImage imageNamed:@"账号-(1)"] forState:(UIControlStateNormal)];
        [btn setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
        [btn setTitle:NSLocalizedString(@"useAccount", nil) forState:UIControlStateNormal];
        [btn.titleLabel setFont:kGeneralFontSize];
        //        btn.hidden = YES;
        [btn addTarget:self action:@selector(accountLoginMethod)
      forControlEvents:(UIControlEventTouchUpInside)];
        self.accountBtn = btn;
    }
    return _accountBtn;
}

//"useTouch" = "使用手势登陆";
- (UIButton *)touchBtn {
    if (!_touchBtn) {
        UIButton * btn = [UIButton new];
        [btn setImage:[UIImage imageNamed:@"手势密码"] forState:(UIControlStateNormal)];
        [btn setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
        [btn setTitle:NSLocalizedString(@"drawGesture", nil) forState:UIControlStateNormal];
        [btn.titleLabel setFont:kGeneralFontSize];
        //        btn.hidden = YES;
        [btn addTarget:self action:@selector(touchLoginMethod)
      forControlEvents:(UIControlEventTouchUpInside)];
        self.touchBtn = btn;
    }
    return _touchBtn;
}

- (UIImageView *)iconView {
    if (!_iconView) {
        self.iconView = [UIImageView new];
        _iconView.image = [UIImage imageNamed:@"指纹"];
    }
    return _iconView;
}
@end
